<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-11-04
 * Time: 9:06
 */

namespace app\helper;


use app\app\constant\AppConstant;
use app\model\AppWxUser;
use think\facade\Cache;
use think\facade\Debug;

class TokenHelper
{
    /**
     * 微信或app设置token的方法
     * @param $uid
     * @param $userInfo
     * @return string 生成的token
     */
    public static function setAppToken($uid, $userInfo)
    {
        $apiAuth = md5(uniqid() . $uid . time());
        //将用户信息保存到redis中，并和token关联
        cache(AppConstant::APP_TOKEN_KEY . $apiAuth, json_encode($userInfo), config('wechat.ONLINE_TIME'));
        //设置之前先清除掉之前的token
//        if (Cache::has(AppConstant::APP_TOKEN_KEY  . $uid)) {
//            $tokenName = Cache::get(AppConstant::APP_TOKEN_KEY  . $uid);
//            cache('Login:' . $tokenName, null);
//        }
        //将token和uid进行关联，方便后台查询
        cache(AppConstant::APP_TOKEN_AND_UID_KEY . $uid, $apiAuth, config('wechat.ACCESS_TOKEN_TIME_OUT'));
        return $apiAuth;
    }
    //更新用户的token信息，这一般是用户信息有变更时才会调用，如充值了VIP
    public static function updateToken($uid)
    {
        $token = cache(AppConstant::APP_TOKEN_AND_UID_KEY . $uid);
        if($token){
            $uesrInfo = AppWxUser::get($uid)->getData();
            $uesrInfo['uid'] = $uesrInfo['id'];
            cache(AppConstant::APP_TOKEN_KEY . $token, json_encode($uesrInfo), config('wechat.ONLINE_TIME'));
        }
    }

    public static function getUserByToken($token)
    {
        $userInfo = cache(AppConstant::APP_TOKEN_KEY . $token);
        $userInfo = json_decode($userInfo, true);
        $cache = Cache::init();
        $pre = config('cache.prefix');
        // 获取缓存对象句柄
        $handler = $cache->handler();
        $exprieTime = $handler->ttl($pre . AppConstant::APP_TOKEN_KEY . $token);
        //为了避免太频繁操作，2分钟更新一次
        if ($exprieTime < (config('wechat.ONLINE_TIME') - 2 * 60)) {
            // 去更新token的过期时间
            $handler->expire($pre . AppConstant::APP_TOKEN_KEY . $token, config('wechat.ONLINE_TIME'));
            $handler->expire($pre . AppConstant::APP_TOKEN_AND_UID_KEY . $userInfo['uid'], config('wechat.ACCESS_TOKEN_TIME_OUT'));
        }
        return $userInfo;
    }

}